<?php

namespace app\api\service;

use addons\xyb\XypHelper;

use app\common\model\daily\UsersModel;
use app\common\model\distributor\Activity as ActivityModel;
use \app\common\model\distributor\Progress as progressModel;
use app\common\model\marketing\MarketingCoupons;
use think\Db;


class DistributorService
{
    /*查询用户可参与的*/
    public static function retrieveActivityInfoOngoing()
    {
        $activity = ActivityModel::getActivityInfo();
        if(!$activity){
            return false;
        }
        if($activity->grant_status != 1){
            return false;
        }
        $activity->inviter_reward = [
            'type'      => (int)$activity->fu_reward_method,
            'point'     => $activity->fu_reward_method == 1 ? (int)$activity->fu_reward_point : 0,
            'youth'     => $activity->fu_reward_method == 2 ? (int)$activity->fu_youth_point : 0,
            'coupons'   => MarketingCoupons::getAssociationCouponsOneArray($activity->fu_reward_coupons_id)
        ];
        $activity->self_reward = [
            'type'      => (int)$activity->reward_method,
            'point'     => $activity->reward_method == 1 ? (int)$activity->reward_point : 0,
            'youth'     => $activity->reward_method == 2 ? (int)$activity->youth_point : 0,
            'coupons'   => MarketingCoupons::getAssociationCouponsOneArray($activity->reward_coupons_id)
        ];
        $activity->share_img = cdnurl($activity->share_img);
        $activity->activity_id = $activity->id;
        return $activity;
    }

    public static function retrieveUsersOngoing($user_id, $circle_id = 0)
    {
       $activity = ActivityModel::getActivityInfo();
       if(!$activity){
           return ['code' => 0, 'msg' => '活动已结束'];
       }
       if($activity->grant_status != 1){
           return ['code' => 0, 'msg' => '活动已结束'];
       }
        $progress = progressModel::where('user_id', $user_id)->where('progress_type', 1)->find();
        $activity->inviter_reward = [
            'type'      => (int)$activity->fu_reward_method,
            'point'     => $activity->fu_reward_method == 1 ? (int)$activity->fu_reward_point : 0,
            'youth'     => $activity->fu_reward_method == 2 ? (int)$activity->fu_youth_point : 0,
            'coupons'   => MarketingCoupons::getAssociationCouponsOneArray($activity->fu_reward_coupons_id)
        ];
        $activity->self_reward = [
            'type'      => (int)$activity->reward_method,
            'point'     => $activity->reward_method == 1 ? (int)$activity->reward_point : 0,
            'youth'     => $activity->reward_method == 2 ? (int)$activity->youth_point : 0,
            'coupons'   => MarketingCoupons::getAssociationCouponsOneArray($activity->reward_coupons_id)
        ];
        $activity->progress_id = (isset($progress) && $progress->id)?$progress->id:0;
        $activity->grant_status = (isset($progress) && $progress->id)?1:0;
        $activity->users_params = ['grant_total'   => 5, 'dynamics_num' => 3];
        $activity->rule_list = self::formatParticipationRules($activity->participation_rules, $activity->users_params);
        $activity->share_img = cdnurl($activity->share_img);
        /*TODO:获取邀请人；获取发布的动态*/
        return $activity;
    }

    /*用户参与活动报名*/
    public static function userRegistrationParticipate($user_id, $circle_id = 0)
    {
        /*获取活动详情*/
        if (!$activity = self::retrieveActivityInfoOngoing()) {
            return ['code' => 0, 'msg' => '无法参与活动'];
        }
        /*查询用户是否有在进行中的任务*/
        $field = 'id,activity_id,jobs_id,user_id,grant_status,deadline_time';
        $progress = progressModel::field($field)->where('user_id', $user_id)->where('progress_type', 1)->find();
        if (!$progress) {
            $res = progressModel::userRegistrationParticipate($user_id);
            if (!$res || !isset($res->id) || !$res->id) {
                return ['code' => 0, 'msg' => '系统繁忙，请稍后再试'];
            }
            return ['code' => 1, 'msg' => '参与成功', 'data' => $res->id];
        }
        return ['code' => 1, 'msg' => '参与成功', 'data' => $progress->id];
    }

    /*邀请人扫码助力*/
    public static function invitePeopleAssist($users_id, $progress_id, $circle_id = 0){
        $assistant = AssistantService::retrieveUsersOngoingTasks($users_id, $circle_id);
        $dynamic = DynamicService::retrieveUsersOngoingTasks($users_id, $circle_id);
        $activity = ActivityModel::getActivityInfo();
        if($activity->grant_status != 1){
            return ['code' => 0, 'msg' => '任务已完成，无法助力', 'data' => ['assistant'=>$assistant->inviter_reward, 'dynamic'=>$dynamic->inviter_reward]];
        }
        $progress = progressModel::where('id', $progress_id)->where('progress_type', 1)->find();
        if($progress && $progress->user_id == $users_id){
            return ['code' => 0, 'msg' => '不能助力自己', 'data' => ['assistant'=>$assistant->inviter_reward, 'dynamic'=>$dynamic->inviter_reward]];
        }
        $res = progressModel::where('progress_id', $progress_id)->where('user_id', $users_id)
            ->where('progress_type', 2)->find();
        if($res){
            return ['code' => 0, 'msg' => '您已助力过了，无法重复助力', 'data' => ['assistant'=>$assistant->inviter_reward, 'dynamic'=>$dynamic->inviter_reward]];
        }
        /*参与用户类型；2=新用户*/
        if($activity->users_method == 2){
            if(!UsersModel::where('id', $users_id)->where('create_time', '>', (time() - 120))->find()){
                if(progressModel::where('user_id', $users_id)->find()){
                    return ['code' => 0, 'msg' => '您不是新用户，无法助力', 'data' => ['assistant'=>$assistant->inviter_reward, 'dynamic'=>$dynamic->inviter_reward]];
                }
            }
        }
        Db::startTrans();
        if(!$self_progress = progressModel::userPeopleRegistrationParticipate($users_id, $progress_id)){
            DB::rollback();
            return ['code' => 0, 'msg' => '任务已结束，无法助力', 'data' => ['assistant'=>$assistant->inviter_reward, 'dynamic'=>$dynamic->inviter_reward]];
        }
        if(!DynamicService::distributeRewardsSelf($users_id, $activity)){
            DB::rollback();
            return ['code' => 0, 'msg' => '任务已结束，无法助力', 'data' => ['assistant'=>$assistant->inviter_reward, 'dynamic'=>$dynamic->inviter_reward]];
        }
        Db::commit();
        $activity->inviter_reward = [
            'type'      => (int)$activity->fu_reward_method,
            'point'     => $activity->fu_reward_method == 1 ? (int)$activity->fu_reward_point : 0,
            'youth'     => $activity->fu_reward_method == 2 ? (int)$activity->fu_youth_point : 0,
            'coupons'   => MarketingCoupons::getAssociationCouponsOneArray($activity->fu_reward_coupons_id)
        ];
        $activity->self_reward = [
            'type'      => (int)$activity->reward_method,
            'point'     => $activity->reward_method == 1 ? (int)$activity->reward_point : 0,
            'youth'     => $activity->reward_method == 2 ? (int)$activity->youth_point : 0,
            'coupons'   => MarketingCoupons::getAssociationCouponsOneArray($activity->reward_coupons_id)
        ];
        return  ['code' => 1, 'msg' => '您获得以下优惠卷', 'data' =>[
            'user_id'           => $progress_id,
            'progress_id'       => $progress_id,
            'self_progress_id'  => (int)$self_progress->id,
            'self_reward'       => $activity->self_reward,
            'inviter_reward'    => $activity->inviter_reward,
            'assistant'         => $assistant->inviter_reward,
            'dynamic'           => $dynamic->inviter_reward
        ]];
    }

    public static function helpList($user_id, $status = 0, $type = 0){
        $field = 'id,id as progress_id,activity_id,jobs_id,grant_status,deadline_time,progress_type';
        $query = progressModel::field($field)->where('progress_id', $user_id)->where('progress_type', 2);
        $progress = $query->order('id desc')->paginate();
        if(!$progress->items()){
            return $progress;
        }
        foreach ($progress as $key => $value){
            $users = UsersModel::field('id,nickname,avatar')->where('id', $value['user_id'])->find();
            $progress[$key]['nickname'] = $users['nickname'];
            $progress[$key]['avatar'] = $users['avatar'];
        }
        return $progress;
    }

    /*格式化邀请规则*/
    public static function formatParticipationRules($participation_rules,$users_params){
        $rules = XypHelper::formatJsonStringToArray($participation_rules);
        $rules_array = [];
        foreach ($rules as $key => $value){
            if(!isset($value['status']) || $value['status'] != 1){
                continue;
            }
            $open_status = 0;
            if(
                (isset($users_params['grant_total']) && $users_params['grant_total'] >= $value['grant_total']) &&
                (isset($users_params['dynamics_num']) && $users_params['dynamics_num'] >= $value['dynamics_num'])
            ){
                $open_status = 1;
            }
            $rules_array[$key] = [
                'type'          => $value['type'],
                'label'         => ActivityModel::$type_method_list[$value['type']],
                'grant_total'   => (isset($value['grant_total']) && $value['grant_total'])?(int)$value['grant_total']:0,
                'dynamics_num'  => (isset($value['dynamics_num']) && $value['dynamics_num'])?(int)$value['dynamics_num']:0,
                'users_method'  => (isset($value['users_method']) && $value['users_method'])?(int)$value['users_method']:1,
                'describe'      => (isset($value['guide']) && $value['guide'])?$value['guide']:'',
                'users_params'  => $users_params,
                'open_status'   => $open_status,
            ];
        }
        return array_values($rules_array);
    }
}